package comnet.ftpclient;

import java.io.*;
import java.net.Socket;

/**
 * @author Mikko Puustinen (mikko.puustinen@gmail.com)
 * @version 0.1, 2008-jan-11
 */
public class DataTransfer {

    /**
     * @param dataSocket
     * @param file
     *
     * @throws IOException
     */
    public void send(Socket dataSocket, File file) throws IOException {
        int numberOfBytes = (int)file.length();
        DataOutputStream os = new DataOutputStream(dataSocket.getOutputStream());
        BufferedInputStream is = null;

        os.writeInt(numberOfBytes);
        os.writeInt(0x20);

        try {
            is = new BufferedInputStream(new FileInputStream(file));
            transferData(is, os, numberOfBytes, dataSocket.getSendBufferSize());
        } finally {
            if (is != null) {
                is.close();
            }
        }
    }

    /**
     * @param dataSocket
     * @param remoteFile
     * @param localFile
     *
     * @throws IOException
     */
    public void receive(Socket dataSocket, String remoteFile, File localFile) throws IOException {
        int numberOfBytes;
        DataInputStream input = new DataInputStream(dataSocket.getInputStream());
        BufferedOutputStream os = null;

        numberOfBytes = input.readInt();
        input.readInt();

        try {
            os = new BufferedOutputStream(new FileOutputStream(localFile));
            transferData(input, os, numberOfBytes, dataSocket.getReceiveBufferSize());
        } finally {
            if (os != null) {
                os.close();
            }
        }
    }

    /**
     * @param is
     * @param os
     * @param numberOfBytes
     * @param bufferSize
     *
     * @throws IOException
     */
    private void transferData(InputStream is, OutputStream os, final int numberOfBytes, final int bufferSize) throws IOException {
        if (is == null || os == null) {
            throw new IllegalArgumentException();
        }
        byte[] buffer = new byte[bufferSize];
        int bytesRead = 0;
        int length;

        while ((length = is.read(buffer)) > 0 && bytesRead < numberOfBytes) {
            os.write(buffer, 0, length);
            bytesRead += length;
        }

        os.flush();
        os.close();
        is.close();
    }
}
